package com.example.testbroadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "网络状态发生改变", Toast.LENGTH_SHORT).show();
    }
}

public class MainActivity extends AppCompatActivity {

    MyBroadcastReceiver _receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //_receiver = new MyBroadcastReceiver();

        // 注册过滤网络状态变化事件
//        IntentFilter filter = new IntentFilter();
//        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
//        registerReceiver(_receiver, filter);
    }

    @Override
    protected void onDestroy() {
        if (_receiver != null)
            unregisterReceiver(_receiver);

        super.onDestroy();
    }

    public void onBroadcastClick(View view) {
        sendBroadcast(new Intent("com.example.testbroadcast.MY_BROADCAST"),
                "com.example.testbroadcast.MY_BROADCAST");
        Log.d("main", "send");
    }
}